package com.vdongchina.thread.base;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 线程第二课
 * 优先级,可能优先级并不能真的让线程优先
 */
public class ThreadPriorityDemo {

    private static volatile boolean notStart = true;
    private static volatile boolean notEnd = true;

    public static void main(String[] args) throws InterruptedException {
        List<Job> jobs = new ArrayList();
        for (int i = 0; i < 10; i++) {
            int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
            Job job = new Job(priority);
            jobs.add(job);
            Thread thread = new Thread(job, "Thread-" + i);
            thread.setPriority(priority);
            thread.start();
        }
        notStart = false;
        TimeUnit.SECONDS.sleep(10);
        notEnd = false;
        for (Job job : jobs) {
            System.out.println("Job priority:" + job.priority + ",Count :" + job.jobCount);
        }
    }


    static class Job implements Runnable {

        private int priority;

        private long jobCount;

        public Job(int priority) {
            this.priority = priority;
        }

        @Override
        public void run() {
            while (notStart) {
                Thread.yield();  //让出当前线程的执行cpu机会, 重新给其他线程进行抢, 自己也会去抢
            }
            while (notEnd) {
                Thread.yield();
                System.out.println("threadname-" + Thread.currentThread().getName());
                jobCount++;
            }

        }
    }


}
